<template>
	<div class="page-container">
		<h1>秒表工具</h1>
		<div class="time-area">{{ time }}</div>
		<div class="button-area">
			<el-button type="primary" @click="start" :disabled="isRunning">开始</el-button>
			<el-button type="primary" @click="lap" :disabled="!isRunning">计次</el-button>
			<el-button type="danger" @click="reset" :disabled="!canReset">复位</el-button>
		</div>
		<div class="laps-area">
			<h2>计次记录</h2>
			<ul>
				<li v-for="(lap, index) in laps" :key="index">{{ lap }}</li>
			</ul>
		</div>
		
	</div>
</template>

<script>
	export default {
		data() {
			return {
				startTime: null,
				timeElapsed: 0,
				timerId: null,
				laps: [],
				isRunning: false
			};
		},
		computed: {
			time() {
				const date = new Date(this.timeElapsed);
				const minutes = date.getUTCMinutes().toString().padStart(2, "0");
				const seconds = date.getUTCSeconds().toString().padStart(2, "0");
				const milliseconds = Math.floor(date.getUTCMilliseconds() / 10)
					.toString()
					.padStart(2, "0");

				return `${minutes}:${seconds}:${milliseconds}`;
			},
			canReset() {
				return this.isRunning || this.laps.length > 0;
			}
		},
		methods: {
			start() {
				this.startTime = Date.now() - this.timeElapsed;
				this.timerId = setInterval(() => {
					this.timeElapsed = Date.now() - this.startTime;
				}, 10);
				this.isRunning = true;
			},
			lap() {
				const lapTime = this.time;
				this.laps.push(lapTime);
			},
			reset() {
				clearInterval(this.timerId);
				this.startTime = null;
				this.timeElapsed = 0;
				this.timerId = null;
				this.laps = [];
				this.isRunning = false;
			}
		}
	};
</script>

<style>
	.time-area {
		font-size: 5rem;
		margin-bottom: 1.5rem;
	}
	
	.laps-area {
		text-align: left;
	}

	ul {
		list-style: none;
	}

	li {
		margin-bottom: 0.5rem;
	}
</style>
